package aiyh.utils.httpUtil.httpAsync;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import aiyh.utils.httpUtil.ExtendedIOUtils;
import aiyh.utils.httpUtil.ResponeVo;

import java.util.Locale;
import java.util.concurrent.Callable;

/**
 * @author EBU7-dev1-ayh
 * @date 2021/9/2 0002 22:55
 * async
 */


public class HttpAsyncThread implements Callable<ResponeVo> {

	private final CloseableHttpClient httpClient;
	private final HttpUriRequest request;
	private String DEFAULT_ENCODING = "UTF-8";

	public HttpAsyncThread(CloseableHttpClient httpClient, HttpUriRequest request, String DEFAULT_ENCODING) {
		this.httpClient = httpClient;
		this.request = request;
		this.DEFAULT_ENCODING = DEFAULT_ENCODING;
	}

	@Override
	public ResponeVo call() throws Exception {
		ResponeVo responeVo = new ResponeVo();
		CloseableHttpResponse response = null;
		try {
			response = httpClient.execute(request);
			HttpEntity entity = response.getEntity();
			Header[] allHeaders = response.getAllHeaders();
			Locale locale = response.getLocale();
			responeVo.setLocale(locale);
			responeVo.setAllHeaders(allHeaders);
			responeVo.setEntityString(EntityUtils.toString(entity, DEFAULT_ENCODING));
			responeVo.setCode(response.getStatusLine().getStatusCode());
		} catch (Exception e) {
			throw e;
		}
		ExtendedIOUtils.closeQuietly(httpClient);
		ExtendedIOUtils.closeQuietly(response);
		return responeVo;
	}
}
